package cn.edu.seu.cose.qol.ws.resource.questionnaire.strategy;

import java.util.Collection;
import java.util.LinkedList;

import cn.edu.seu.cose.qol.model.dao.database.question.ShortAnswerDataAccess;
import cn.edu.seu.cose.qol.model.dto.question.AddressableQuestionInstance;
import cn.edu.seu.cose.qol.model.dto.question.QuestionBaseInstance;
import cn.edu.seu.cose.qol.model.dto.question.QuestionContentType;
import cn.edu.seu.cose.qol.model.dto.question.QuestionInstance;
import cn.edu.seu.cose.qol.model.po.question.ShortAnswer;

class ShortAnswerStrategy implements QuestionBaseStrategy {
	
	private ShortAnswerDataAccess _dataAccess;

	@Override
	public QuestionBaseInstance getQuestionBase(String questionnaireName)
			throws Exception {
		Collection<ShortAnswer> shortAnswers =
				_dataAccess.getShortAnswers();
		LinkedList<AddressableQuestionInstance> addressableQuestions =
				new LinkedList<AddressableQuestionInstance>();
		for (ShortAnswer shortAnswer: shortAnswers) {
			AddressableQuestionInstance qi =
					getQuestionByShortAnswer(shortAnswer, questionnaireName);
			addressableQuestions.add(qi);
		}
		
		QuestionBaseInstance instance = new QuestionBaseInstance();
		instance.setAddressableQuestions(addressableQuestions.toArray(
				new AddressableQuestionInstance[0]));
		instance.setName(QuestionBaseStrategyFactory.SHORT_ANSWER);
		return instance;
	}

	@Override
	public void createNewQuestion(QuestionInstance questionInstance,
			String questionnaireName) throws Exception {
		QuestionContentType contentType =
				questionInstance.getContentType();
		if (!QuestionContentType.SHORT_ANSWER.equals(contentType)) {
			throw new QuestionTypeNotSupported(contentType);
		}
	}

	@Override
	public void deleteQuestions(String questionnaireName) throws Exception {
		// TODO Auto-generated method stub
		
	}
	
	private AddressableQuestionInstance getQuestionByShortAnswer(
			ShortAnswer shortAnswer, String questionnaireName) {
		String questionTitle = shortAnswer.getQuestionTitle();
		long id = shortAnswer.getShortAnswerId();
		
		QuestionUriBuilder builder = QuestionUriBuilder.getInstance();
		
		AddressableQuestionInstance question =
				new AddressableQuestionInstance();
		question.setContentType(QuestionContentType.SHORT_ANSWER);
		question.setBody(questionTitle);
		question.setUri(builder.getUri(
				questionnaireName,
				QuestionBaseStrategyFactory.SHORT_ANSWER,
				String.valueOf(id)));
		
		return question;
	}

}
